package online.inote.naruto.api.access.admin.modules.system.service;

import online.inote.naruto.api.access.admin.modules.system.entity.AuthInterfaceEntity;
import online.inote.naruto.api.access.admin.modules.system.repository.AuthInterfaceRepository;
import online.inote.naruto.api.access.props.ApiAccessProperties;
import online.inote.naruto.cache.CacheSupport;
import online.inote.naruto.utils.Assert;
import online.inote.naruto.utils.DateTimeUtils;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @description 系统授权接口Service
 * @author XQF.Sui
 * @date 2021/08/06 19:26
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class AuthInterfaceService {

  private final ApiAccessProperties apiProps;
  private final AuthInterfaceRepository repository;

  public AuthInterfaceService(ApiAccessProperties apiProps, AuthInterfaceRepository repository) {
    this.apiProps = apiProps;
    this.repository = repository;
  }

  public void save(AuthInterfaceEntity aie) {
    aie.setCreateTime(DateTimeUtils.getNow());
    aie.genSignatureDigest();

    if (apiProps.getDatabase().getEnable()) {
      List<AuthInterfaceEntity> authEntities =
          repository.findAllBySystemIdAndApiId(aie.getSystemId(), aie.getApiId());

      if (CollectionUtils.isEmpty(authEntities)) {
        repository.save(aie);
      }

      CacheSupport.addSet(
          apiProps.getCache().initSystemAuthInterfacePathCacheKey(aie.getSystemId()),
          aie.getClassMethod());

      CacheSupport.addSet(
          apiProps.getCache().initInterfaceAuthSystemCacheKey(aie.getApiId()), aie.getSystemId());
    }
  }

  public void delete(AuthInterfaceEntity aie) {
    if (apiProps.getDatabase().getEnable()) {
      repository.deleteBySystemIdAndApiId(aie.getSystemId(), aie.getApiId());
    }

    CacheSupport.remove(
        apiProps.getCache().initSystemAuthInterfacePathCacheKey(aie.getSystemId()),
        aie.getClassMethod());

    CacheSupport.remove(
        apiProps.getCache().initInterfaceAuthSystemCacheKey(aie.getApiId()), aie.getSystemId());
  }

  public List<AuthInterfaceEntity> findBySystemId(String systemId) {
    Assert.notBlank(systemId, "系统ID不能为空");

    Example<? extends AuthInterfaceEntity> example =
        Example.of(AuthInterfaceEntity.builder().systemId(systemId).build());

    List<? extends AuthInterfaceEntity> authInterfaceEntities = repository.findAll(example);

    return (List<AuthInterfaceEntity>) authInterfaceEntities;
  }
}
